import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const request = axios.create({
  baseURL: 'http://api-toutiao-web.itheima.net',
  timeout: '5000'
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    NProgress.start()
    config.headers.Authorization = store.state.userInfo
      ? `Bearer ${store.state.userInfo.token}`
      : ''
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  config => {
    NProgress.done()
    return config
  },
  error => {
    if (error.message === 'timeout of 5000ms exceeded') {
      Message.error('服务器忙,请稍后再试!')
    }
    return Promise.reject(error)
  }
)
export { request }
